
#pragma once
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <iostream>
#include <unistd.h>
#include <arpa/inet.h>
#include <functional>

typedef std::function<void(int,std::string,uint16_t,std::string)> func_t;

class UdpServer
{
private:
    int _sock; 
    uint16_t _port;
    func_t _callback;
public:
    UdpServer(uint16_t port,func_t callback): _port(port) ,_callback(callback){ }
    ~UdpServer() { close(_sock); }
    void init()
    {
        _sock = socket(AF_INET,SOCK_DGRAM,0);  //创建套接字
        if(_sock < 0)
        {
            //创建失败
            std::cout << "create socket failed...." << std::endl;
            abort();
        }
        //绑定 
        struct sockaddr_in ser; 
        ser.sin_port = htons(_port);  //填入端口
        ser.sin_family = AF_INET; // 填入域
        ser.sin_addr.s_addr = INADDR_ANY; //填入IP地址
        if(bind(_sock,(sockaddr*)&ser,sizeof ser) != 0) //绑定
        {
            //绑定失败
            std::cout << "bind socket failed...." << std::endl;
            abort();
        }
    }

    void start()
    {
        struct sockaddr_in peer; //对端
        socklen_t peer_len = sizeof peer;
        char buff[1024] = {0};   
        while(1)
        {
            int n = recvfrom(_sock,buff,1023,0,(struct sockaddr*)&peer,&peer_len); 
            buff[n] = 0;
            if(read == 0)
            {
                std::cout << "one client quit..." << std::endl;
                continue;
            }else if(read < 0)
            {
                 std::cout << "read error..." << std::endl;
                 break;
            }
            //获取客户端的端口和IP
            std::string clientip = inet_ntoa(peer.sin_addr);
            uint16_t clientport = ntohs(peer.sin_port);
            std::cout << buff << std::endl; //回显客户端信息
            //调用回调函数处理数据
            _callback(_sock,clientip,clientport,buff);
        }
    } 
};